var roomsList;
var sh;
var gridObj;
var gridFormObject;
var layerGridFormIndex;
var opt = '';

$(function() {
	initCommunity();
	initHouse();

	roomsList = roomList;

	gridObj = $.fn.bsgrid.init('searchTable', {
		pageSize : pageSize,
		// 可调整成ajax请求
		localData : list,
		event : {
			customCellEditEvents : {
				click : function(formObj, record, rowIndex, colIndex, tdObj, trObj, options) {
					if (colIndex == 1) {
						$("#selectRoomNo" + rowIndex).select2({
							language : "zh-CN",
							allowClear : true,
							ajax : {
								url : '/CMS/select/getHouseList.ht',
								dataType : 'json',
								delay : 250,
								data : function(param) {
									return {
										search : param.term,
										page : param.page || 1,
										cid : function() {
											// 注意这里的小区不是下拉列表框中的小区,而是列表数据的来源小区
											return communityId || '';
										},
									};
								},
								processResults : function(data, param) {
									param.page = data.nextPage;
									return {
										results : data.list,
										pagination : {
											more : data.hasNextPage
										}
									};
								}
							},
							escapeMarkup : function(markup) {
								return markup;
							},
							templateResult : formatRepo,
							// 显示查询结果
							templateSelection : function(obj) {
								$("#selectRoomNo" + rowIndex).append("<option selected='selected' value='" + obj.id + "'>" + obj.name + "</option>");
								$("#selectRoomNo" + rowIndex).val(obj.id);
								$("#select2-selectRoomNo" + rowIndex + "-container").html(obj.name);
								// gridObj.refshTable();
								return obj.name || obj.text;
							}

						});
					}
					if (colIndex == 2) {
						var valll = ""
						$("#selectAmCharge" + rowIndex).select2();
						if (roomsList) {
							$.each(roomsList, function(name, ve) {
								if (record.hid == ve.hid) {
									valll = ve.roomNo;
									return false;
								}
							});
							$("#select2-selectRoomNo" + rowIndex + "-container").html(valll);
						}
					}

				}
			}
		},
		extend : {
			settings : {
				supportGridEdit : (userType == '2' || userType == '3') ? true : false,
				// 是否支持编辑
				supportGridEditTriggerEvent : 'rowDoubleClick',
				// default 'rowClick', values: ''(means no need Trigger), 'rowClick', 'rowDoubleClick', 'cellClick', 'cellDoubleClick'
				gridEditConfigs : {
					selectRoomNo : selectRoomNo,
					selectAmCharge : selectAmCharge,
					readLast : readLast,
					text : text
				},
				// 特殊配置！！！房屋名称和房号对应关系，针对selectRoomNo配置。类推，和状态下拉框有区别。
				custSelect : {
					"roomNo" : "hid"
				}
			}
		}
	});

	// createChargeNoOption();
	if ((!document.getElementById("selectRoomNo0")) || $("#selectRoomNo0").parent().parent().children().eq("5").find(".redddd")) {
		sh = setInterval(bianse, 100);
	}

	// 导入文件选择/更改时，显示文件信息。以方便用户检查
	$("#importFile").change(function() {
		var filename = $(this).val() || '';
		if (filename != '') {
			$("#selectedImportedFileName").html('当前选择的文件：' + filename);
		} else {
			$("#selectedImportedFileName").html('');
		}
	});
});

if (roomsList) {
	$.each(roomsList, function(name, ve) {
		opt = opt + '<option selected value="' + ve.hid + '">' + ve.roomNo + '</option>';
	});
}

function wordCount(obj) {
	var last = "lastAmmeter" + obj;
	var newbb = "newAmmeter" + obj;
	var lastVal = $("#" + last + "").val();
	var newVal = $("#" + newbb + "").val();
	var length = newVal - lastVal;
	if (length <= 0) {
		length = 0;
	}
	length = Math.round(length * 100) / 100;
	if (length >= 50) {
		$("#" + last + "").parent().parent().children().eq("5").html("<span style='color:red;'>" + length + "</span>");
	} else {
		$("#" + last + "").parent().parent().children().eq("5").html("<span>" + length + "</span>");
	}
}

// 选择房号
selectRoomNo = {
	build : function(edit, value, record, rowIndex, colIndex, tdObj, trObj, options) {
		var val = value + '<select hid=' + record.hid + ' onchange="checkTest(' + rowIndex + ');" class="' + 'bsgrid_editgrid_edit select2Click" style="width: 203px;" id="selectRoomNo' + rowIndex + '" name="selectRoomNo' + rowIndex + '">';
		val = val + '</select>'
		return val;
	},
	val : function(formObj) {
		return formObj.val();
	}
}

// 选择房屋
function selectRoomInit(rowIndex) {
	$("#selectRoom" + rowIndex).append(opt);
}

// 房号转义
function getRoom(record, rowIndex, colIndex, options) {
	var val = '';
	if (!roomsList) {
		return '';
	}
	$.each(roomsList, function(name, ve) {
		if (record.hid == ve.hid) {
			val = ve.roomNo;
			return false;
		}
	});
	return val;
}

function closeLayer(obj) {
	$("#" + obj).css("display", "none");
}

// 账单状态
textSta = {
	build : function(edit, value, record, rowIndex, colIndex, tdObj, trObj, options) {
		return value + '<input class="bsgrid_editgrid_edit" style="width: 100px;" id="status' + rowIndex + '" type="' + edit + '" value="' + value + '"/>'
	},
	val : function(formObj) {
		return formObj.val()
	}
}

// 表类型
selectAmCharge = {
	build : function(edit, value, record, rowIndex, colIndex, tdObj, trObj, options) {
		var val = value + '<select onchange="checkTest(' + rowIndex + ');" class="' + 'bsgrid_editgrid_edit select2Click" style="width: 146px;" id="selectAmCharge' + rowIndex + '" name="selectAmCharge' + rowIndex + '">';
		var opt = '';
		if (chargeList == undefined) {
			return;
		}
		$.each(chargeList, function(name, ve) {
			if (record.chargeId == ve.dictValue) {
				opt = opt + '<option selected value="' + ve.dictValue + '">' + ve.dictDestination + '</option>';
			} else {
				opt = opt + '<option value="' + ve.dictValue + '">' + ve.dictDestination + '</option>';
			}
		});
		val = val + opt + '</select>';
		return val;
	},
	val : function(formObj) {
		return formObj.val();
	}
}

// 表类型转义
function getAmCharge(record, rowIndex, colIndex, options) {
	var val = '';
	if (chargeList == undefined) {
		return;
	}
	$.each(chargeList, function(name, ve) {
		if (record.chargeId == ve.dictValue) {
			val = ve.dictDestination;
			return false;
		}
	});
	return val;
}

readLast = {
	build : function(edit, value, record, rowIndex, colIndex, tdObj, trObj, options) {
		return value + '<input oninput="wordCount(' + rowIndex + ');" class="bsgrid_editgrid_edit" maxlength="10" id="lastAmmeter' + rowIndex + '" type="' + edit + '" value="' + value + '"/>'
	},
	val : function(formObj) {
		return formObj.val()
	}
}

text = {
	build : function(edit, value, record, rowIndex, colIndex, tdObj, trObj, options) {
		return value + '<input oninput="wordCount(' + rowIndex + ');" class="bsgrid_editgrid_edit" maxlength="10" id="newAmmeter' + rowIndex + '" type="' + edit + '" value="' + value + '"/>'
	},
	val : function(formObj) {
		return formObj.val()
	}
}

function checkTest(num) {
	var hid = "selectRoomNo" + num;
	var chargeId = "selectAmCharge" + num;
	var lastId = "lastAmmeter" + num;
	var newId = "newAmmeter" + num;
	var _url = '/CMS/ammeterListReading/searchAmmeterLastReading.ht';
	var hidd = $("#" + hid + "").val();
	if (!hidd) {
		hidd = $("#" + hid).attr("hid");
	}
	$(gridObj.getRow(num)).each(function() {
		$(this).removeClass("bsgrid_editgrid_change")
	})
	gridObj.getRow(num).data("change");

	$(gridObj.getRow(num)).attr('title', '');
	$(gridObj.getRow(num)).poshytip("destroy");
	// 刷新
	$.ajax({
		url : _url,
		data : {
			"hid" : hidd,
			"chargeId" : $("#" + chargeId).val()
		},
		type : 'POST',
		beforeSend : showProccessBar,
		error : hideProccessBar,
		success : function(data) {
			$("#" + newId).attr("value", "0").change();
			$("#" + lastId).attr("value", data.lastRead).change();
			wordCount(num);
			hideProccessBar();
		}
	});

}

function bianse() {
	$("#searchTable").find("tr").each(function() {
		var parseint = parseInt($(this).children().eq("5").html());
		if (parseint >= 50) {
			$(this).children().eq("5").css("color", "red");
		}
	});
	clearInterval(sh);
}

function add() {
	if (roomsList && roomsList.length == 0) {
		_alert('没有房屋信息！');
		return;
	}
	var _url = '/CMS/ammeterListReading/searchAmmeterLastReading.ht';
	var mydate = new Date().format("yyyyMMdd");
	$.ajax({
		url : _url,
		data : {
			"hid" : roomsList[0].hid,
			"chargeId" : chargeList[0].dictValue
		},
		type : 'POST',
		beforeSend : showProccessBar,
		error : hideProccessBar,
		success : function(data) {
			var newRec = {
				hid : roomsList[0].hid,
				chargeId : chargeList[0].dictValue,
				lastReading : data.lastRead,
				thisReading : "0",
				pkFixedId : "",
				amDate : mydate,
				markName : isAcMark[1].dictDestination
			};
			gridObj.addLoadGridData(newRec);
			if ((!document.getElementById("selectRoomNo0")) || $("#selectRoomNo0").parent().parent().children().eq("5").find(".redddd")) {
				sh = setInterval(bianse, 100);
			}
			hideProccessBar();
		}
	});
}

// 保存（添加、修改）
function saveRow() {
	$("#saveInfo").css("disabled", true);
	var editUrl = '/CMS/ammeterListEdit/doEdit.ht' + "?cid=" + $("#cidForHidden").val();
	var flag = false;
	var arr = [];
	var rowIdx = null;
	// 获取变动后的数据
	$.each(gridObj.getRowsChangedColumnsValue(), function(key, object) {
		rowIdx = key.replace("row_", "");
		var rowIdx_ = parseInt(rowIdx) + 1;
		var rec = gridObj.getRecord(rowIdx);
		if (object.lastReading) {
			if (!bmsValidata.float1(object.lastReading)) {
				_alert("第" + rowIdx_ + "行，请输入正确的上次读数，不得少于0");
				flag = true;
				$("#saveInfo").css("disabled", false);
				return false;
			}
		} else if (!rec.lastReading) {
			_alert("第" + rowIdx_ + "行，请输入正确的上次读数，不得为空");
			flag = true;
			$("#saveInfo").css("disabled", false);
			return false;
		}
		if (object.thisReading) {
			if (!bmsValidata.float1(object.thisReading)) {
				_alert("第" + rowIdx_ + "行，请输入正确的本次读数，不得少于0");
				flag = true;
				$("#saveInfo").css("disabled", false);
				return false;
			}
		} else if (!rec.thisReading) {
			_alert("第" + rowIdx_ + "行，请输入正确的本次读数，不得为空");
			flag = true;
			$("#saveInfo").css("disabled", false);
			return false;
		}
		if (parseFloat(rec.lastReading) > parseFloat(rec.thisReading)) {
			_alert("第" + rowIdx_ + "行，本次读数不得少于上次读数");
			$("#saveInfo").css("disabled", false);
			return;
		}
		// 添加下标
		object._idx = rowIdx;
		object.amId = rec.amId;
		object.hid = rec.hid;
		object.chargeId = rec.chargeId;
		object.lastReading = rec.lastReading;
		object.thisReading = rec.thisReading;
		object.amDate = rec.amDate;
		object.markName = rec.markName;
		object.gap = rec.thisReading - rec.lastReading;
		arr.push(object);
	});

	if (flag) {
		var url = '/CMS/ammeter/showList.ht' + "?cidForHidden=" + $("#cidForHidden").val();
		$.go(url, {
			dataType : 'html',
			beforeSend : showProccessBar,
			error : hideProccessBar,
			success : function(data, textStatus) {
				replaceDocument(url, data);
			}
		});
	} else if (arr.length == 0) {
		gridObj.refreshPage();
		var url = '/CMS/ammeter/showList.ht' + "?cidForHidden=" + $("#cidForHidden").val();
		$.go(url, {
			dataType : 'html',
			beforeSend : showProccessBar,
			error : hideProccessBar,
			success : function(data, textStatus) {
				replaceDocument(url, data);
			}
		});
	} else {
		editTabAjax1(editUrl, arr);
	}
	$("#saveInfo").css("disabled", false);
}

function editTabAjax1(editUrl, arr, back) {
	var flag = '1';
	$.ajax({
		url : editUrl,
		data : JSON.stringify(arr),
		type : "post",
		dataType : "json",
		contentType : "application/json",
		beforeSend : showProccessBar,
		error : hideProccessBar,
		success : function(data) {
			var code = data.code;
			if (code == message_false_code) {
				_alert(data.message);
				hideProccessBar();
				return false;
			} else {
				var result = data.result;
				// 成功的
				$.each(result, function(key, object) {
					if (!object._sucflag && object._sucflag == 0) {
						var red = gridObj.getRecord(object._idx);
						red._sucflag = object._sucflag;
						$.extend(red, object);
						// 移除更改样式
						$(gridObj.getRow(object._idx)).each(function() {
							$(this).removeClass("bsgrid_editgrid_change")
						})
						gridObj.getRow(object._idx).data("change");

						$(gridObj.getRow(object._idx)).attr('title', '');
						$(gridObj.getRow(object._idx)).poshytip("destroy");
						// 刷新
						gridObj.refshTable();

					}
				});

				$.each(result, function(key, object) {
					if (!object._sucflag && object._sucflag == 0) {
						return;
					}
					// 失败的
					var red = gridObj.getRecord(object._idx);
					red._sucflag = object._sucflag;
					$.extend(red, object);
					$(gridObj.getRow(object._idx)).attr('title', object._msg);
					$(gridObj.getRow(object._idx)).poshytip({
						className : 'tip-darkgray',
						alignTo : 'target',
						alignX : 'center',
						offsetY : 5,
						allowTipHover : false,
						showTimeout : 1
					});
					$(gridObj.getRow(object._idx)).mouseenter();
					flag = '2'
				});

				if (flag == '1') {
					var url = '/CMS/ammeter/showList.ht' + "?cidForHidden=" + $("#cidForHidden").val();
					$.go(url, {
						dataType : 'html',
						beforeSend : showProccessBar,
						error : hideProccessBar,
						success : function(data, textStatus) {
							replaceDocument(url, data);
						}
					});
				}
				sh = setInterval(bianse, 100);
				try {
					back(data);
				} catch (e) {

				} finally {
					hideProccessBar();
				}
			}
		}
	});
}

// 删除
function deleteRowByCheck() {
	if (gridObj.getCheckedRowsIndexs().length == 0) {
		_alert('请选择要删除的记录');
		return false;
	}
	var pkId = 'amId';
	var delUrl = '/CMS/ammeterListDelete/doDelete.ht';
	deleteTabByAjax1(gridObj, delUrl, pkId);
}

function deleteTabByAjax1(gridObj, delUrl, pkId) {
	_confirm("<span style='color:#FE6600'>确认删除？</span>", function() {
		var records = gridObj.getCheckedRowsRecords();
		var arr = [];
		for (var i = 0; i < records.length; i++) {
			var pk = gridObj.getRecordIndexValue(records[i], pkId);
			if (pk) {
				arr.push(pk);
			}
		}
		var idx = gridObj.getCheckedRowsIndexs();
		var ids = arr.join(",");
		if (ids.length == 0) {
			if (idx.length > 0) {
				for (var i = idx.length - 1; i >= 0; i--) {
					var index = idx[i];
					try {
						$(gridObj.getRow(index)).attr('title', '');
						$(gridObj.getRow(index)).poshytip("destroy");
					} catch (e) {
					}
					gridObj.deleteRow(index);
					// gridObj.getAllRecords()[index] = null;
				}
				return false;
			} else {
				return false;
			}
		}
		$.ajax({
			url : delUrl,
			data : {
				ids : ids
			},
			beforeSend : function() {
				showProccessBar();
			},
			error : function() {
				hideProccessBar();
			},
			success : function(data) {
				var code = data.code;
				if (code == message_false_code) {
					_alert(data.message);
					var url = '/CMS/ammeter/showList.ht' + "?cidForHidden=" + $("#cidForHidden").val();
					$.go(url, {
						dataType : 'html',
						error : function() {
							hideProccessBar();
						},
						success : function(data, textStatus) {
							replaceDocument(url, data);
						}
					});
					return;
				} else {
					for (var i = idx.length - 1; i >= 0; i--) {
						var index = idx[i];
						try {
							$(gridObj.getRow(index)).attr('title', '');
							$(gridObj.getRow(index)).poshytip("destroy");
						} catch (e) {
						}
						gridObj.deleteRow(index);
						// gridObj.getAllRecords()[index] = null;
					}
					_alert(data.message);
					var url = '/CMS/ammeter/showList.ht' + "?cidForHidden=" + $("#cidForHidden").val();
					$.go(url, {
						dataType : 'html',
						error : function() {
							hideProccessBar();
						},
						success : function(data, textStatus) {
							replaceDocument(url, data);
						}
					});
				}
			}
		});
	});
}

// 打开下载模板的对话框
function exportAm() {
	// 小区
	$("#export_cidSelect").empty();
	if (!$("#export_cidSelect").data('select2')) {
		$("#export_cidSelect").select2({
			placeholder : '请选择小区',
			language : "zh-CN",
			allowClear : true,
			ajax : {
				url : '/CMS/select/getCommunityList.ht',
				dataType : 'json',
				delay : 250,
				data : function(param) {
					return {
						search : param.term,
						page : param.page || 1,
						showAllItem : true
					};
				},
				processResults : function(data, param) {
					param.page = data.pageNum;
					return {
						results : data.list,
						pagination : {
							more : data.hasNextPage
						}
					};
				}
			},
			escapeMarkup : function(markup) {
				return markup;
			},
			templateResult : formatRepo,
			templateSelection : function(obj) {
				$("#export_cid").val(obj.id || '');
				return obj.name || obj.text;
			}
		});

		$("#export_cidSelect").change(function() {
			getBuildingArray($(this).val() || '');
		});
	}
	$("#export_cidSelect").select2('val', '');

	// 楼栋
	$("#export_buildingNoSelect").empty();
	$("#export_buildingNoSelect").select2({
		placeholder : '请选择楼栋',
		language : "zh-CN",
		allowClear : true,
		data : [],
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#export_buildingNo").val(obj.id || '');
			return obj.name || obj.text;
		}
	});
	$("#export_buildingNoSelect").select2('val', '');

	// 单元
	$("#export_buildingUnitSelect").empty()

	$("#export_buildingUnitSelect").select2({
		placeholder : '请选择单元',
		language : "zh-CN",
		allowClear : true,
		data : [],
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#export_buildingUnit").val(obj.id || '');
			return obj.name || obj.text;
		}
	});
	$("#export_buildingUnitSelect").select2('val', '');

	// 房号
	$("#export_buildingNumSelect").empty();
	$("#export_buildingNumSelect").select2({
		placeholder : '请选择房号',
		language : "zh-CN",
		allowClear : true,
		data : [],
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#export_buildingNum").val(obj.id || '');
			return obj.name || obj.text;
		}
	});
	$("#export_buildingNumSelect").select2('val', '');

	var array = [];

	var allChargeNo = {};
	allChargeNo.id = ' ';
	allChargeNo.name = '全部类型';
	allChargeNo.text = '全部类型';
	array.push(allChargeNo);

	$.each(chargeList, function(index) {
		var id = chargeList[index].dictValue;
		var name = chargeList[index].dictDestination;
		var option = {};
		option.id = id;
		option.name = name;
		option.text = text;

		array.push(option);
	});

	// 表类型
	$("#export_amChargeNoSelect").empty();

	$("#export_amChargeNoSelect").select2({
		placeholder : '请选择表类型',
		language : "zh-CN",
		allowClear : true,
		data : array,
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#export_amChargeNo").val(obj.id || '');
			return obj.name || obj.text;
		}
	});
	$("#export_amChargeNoSelect").select2('val', '');

	$("#ks-pop-box-amt").show();
}

// 提交下载模板
function expAmt() {
	if (($("#export_cid").val() || '') == '') {
		_alert("请选择小区");
		return;
	}
	var cid = $("#export_cid").val() || '';
	var floor = $("#export_buildingNo").val() || '';
	var unit = $("#export_buildingUnit").val() || '';
	var hid = $("#export_buildingNum").val() || '';
	var type = $("#export_amChargeNo").val() || '';
	var controlUrl = '/CMS/ammeterListExport/exportTemplatesForImport.ht';
	var url = controlUrl + "?cid=" + cid + "&floor=" + floor + "&unit=" + unit + "&hid=" + hid + "&type=" + type;
	$.ajax({
		url : '/CMS/securityProtect/check.ht',
		data : {
			url : controlUrl
		},
		beforeSend : function() {
			showProccessBar();
		},
		complete : function() {
			hideProccessBar();
		},
		success : function() {
			window.open(url);
		}
	});

}

function openImport() {
	$("#ks-pop-box3").show();
}

function closeLayer(obj) {
	$("#" + obj).css("display", "none");
}

var importing = false;

function importAm___delete() {
	if (!$("#importFile").val()) {
		_alert("请选择抄表导入模板。若没有模板，请点击导出");
		return;
	}
	if (importing) {
		var url = '/CMS/ammeter/showList.ht';
		$.go(url, {
			dataType : 'html',
			beforeSend : function() {
				showProccessBar();
			},
			error : function() {
				hideProccessBar();
			},
			success : function(data, textStatus) {
				replaceDocument(url, data);
			}
		});
		return;
	}

	importing = true;
	$.submit($("#importForm"), {
		dataType : 'json',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			importing = false;
			layer.alert(data.message, {
				closeBtn : false,
				area : [ '250px', '200px' ],
				offset : '220px'
			}, function() {
				var f = document.getElementById("frm");
				f.action = '/CMS/ammeter/showList.ht';
				$.submit(f, {
					dataType : 'html',
					error : hideProccessBar,
					success : function(data, textStatus) {
						var url = f.attr('action');
						replaceDocument(url, data);
					}
				});
			});
		}
	});
}

/* 账单导入和账单删除js */
var rowNumber = 1;
var lineNumber = 1;
var aryMid = [];
var st = $("#newMap").val();

var importing = false;

function importAm() {
	var fileName = $("#importFile").val();
	if (!(fileName.lastIndexOf(".xls") > 0)) {
		_alert("只能导入模板xls文件");
		return;
	}
	if (!$("#importFile").val()) {
		_alert("请选择账单导入模板。若没有模板，请点击导出");
		return;
	}
	if (importing) {
		var url = '/CMS/ammeter/showList.ht';
		$.go(url, {
			dataType : 'html',
			beforeSend : function() {
				showProccessBar();
			},
			error : function() {
				hideProccessBar();
			},
			success : function(data, textStatus) {
				replaceDocument(url, data);
			}
		});
		return;
	}

	importing = true;
	$.submit($("#importForm"), {
		dataType : 'json',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			if (data.code == "0") {
				if (data.message != null && data.message != "") {
					_alert("账单正在导入，请稍后查看！" + data.message + "未生成成功", true);
					window.location.reload();
				} else {
					_alert("账单正在导入，请稍后查看！", true);
					window.location.reload();
				}
			} else {
				_alert("发生错误，" + data.message);
				window.location.reload();
			}
		}
	});
}

// 刷新页面
function reloadHtml() {
	window.location.reload();
}

// 删除行
function DelRow() {
	if (rowNumber <= 1) {
		_alert("至少保留一个");
		return false;
	}
	var getRow = window.event.srcElement.parentElement.parentElement.rowIndex;
	categoryTable.deleteRow(getRow);
	lineNumber = lineNumber - 1;
	rowNumber = rowNumber - 1;
	$("#rowNumber").val(rowNumber);
}

// 上移一行
function Move_up(src) {
	var rowIndex = src.parentElement.parentElement.rowIndex;
	if (rowIndex >= 2)
		change_row(rowIndex - 1, rowIndex);
}

// 下移一行
function Move_down(src) {
	var rowIndex = src.parentElement.parentElement.rowIndex;
	var tl = document.getElementById("categoryTable");
	if (rowIndex < tl.rows.length - 1)
		change_row(rowIndex + 1, rowIndex);
}

// 交换行数
function change_row(line1, line2) {
	categoryTable.rows[line1].swapNode(categoryTable.rows[line2]);
}

// 动态添加行数
function AddNewCategory() {
	var array = aryMid;
	if (rowNumber > 4) {
		_alert("最多新增5个");
		return false;
	}
	var sourceNode = $("#parent");
	var clonedNode = sourceNode.clone(true);
	var parent = "parent" + lineNumber;
	if ($("#" + parent + "").size() > 0) {
		lineNumber = lineNumber + 1;
		parent = "parent" + lineNumber;
	}
	$("#categoryTable").append(
			"<tr id='" + parent + "'><td style='text-align: center; width: 112px;'><select class='searchForBiLL' style='width: 112px;' name='s1" + lineNumber + "' id='s1" + lineNumber + "' onchange=\"init('s1" + lineNumber + "','s2" + lineNumber + "',1)\"><option  value='0'>请选择楼栋</option></select ></td><td style='text-align: center; width: 112px;'><select class='searchForBiLL' style='width: 112px;' name='s2" + lineNumber + "' id='s2" + lineNumber + "' onchange=\"init('s2" + lineNumber + "','s3"
					+ lineNumber + "',2)\"><option  value='0'>请选择单元</option></select style='width: 112px;'></td><td style='text-align: center; width: 112px;'><select class='searchForBiLL' style='width: 112px;' name='s3" + lineNumber + "' id='s3" + lineNumber
					+ "'><option value='0'>请选择房号</option></select></td><td  style='text-align:center;width: 112px;'><input type='button' value='新增' onclick='AddNewCategory()' style='width:80px;'/></td><td  style='text-align:center;width: 112px;'><input type='button' value='删除' onclick='DelRow()' style='width:80px;'/></td></tr>");
	var repeat = [];
	for (var i = 0; i < array.length; i++) {
		// 去掉重复值
		repeat.push(array[i][0]);
	}
	var checkRepeat = unique(repeat);
	for (var i = 0; i < checkRepeat.length; i++) {
		$("#s1" + lineNumber + "").append("<option value='" + checkRepeat[i] + "'>" + checkRepeat[i] + "</option>");
	}
	// 每添加一个，初始化一个
	lineNumber = lineNumber + 1;
	rowNumber = rowNumber + 1;
	$("#rowNumber").val(lineNumber);
	setTimeout(function() {
		$(".searchForBiLL").select2();
	}, 1);
}

function importMeterReading() {
	var fileName = $("#importFile").val();
	if (!(fileName.lastIndexOf(".xls") > 0)) {
		_alert("只能导入模板xls文件");
		return;
	}
	if (!$("#importFile").val()) {
		_alert("请选择抄表记录导入模板。若没有模板，请点击导出");
		return;
	}
	showProccessBar();
	$.submit($("#importForm"), {
		dataType : 'json',
		beforeSend : function() {
			showProccessBar();
		},
		error : function() {
			hideProccessBar();
		},
		success : function(data, textStatus) {
			$("#ks-pop-box3").css("display", "none");
			if (data.result != null) {
				var rvrDtoList = data.result.rvrDtoList;
				var errorRowSize = rvrDtoList.length;
				if (errorRowSize > 0) {
					$("#importMeterReadingResultDiv").show();
					$("#importMeterReadingResultTab tr:not(:first)").empty();

					var repeatRowSize = 0;
					for (var i = 0; i < errorRowSize; i++) {
						var errorRow = rvrDtoList[i];
						var errorCol = errorRow.cvrDtoList;
						var errorColSize = errorCol.length;

						var newRow = "<tr><td align='center' rowspan=" + errorColSize + ">" + errorRow.rowMarker + "</td><td>" + errorCol[0].errorMsg + "</td></tr>";
						for (var j = 1; j < errorColSize; j++) {
							newRow += "<tr><td>" + errorCol[j].errorMsg + "</td></tr>";
						}
						$("#importMeterReadingResultTab tr:last").after(newRow);
						repeatRowSize += errorRow.rowMarker.split(",").length - 1;
					}

					errorRowSize += repeatRowSize;

					$("#allImportCount").html(data.result.totalCount);
					$("#successImportCount").html(data.result.totalCount - errorRowSize);
					$("#failedImportCount").html(errorRowSize);
				} else {
					$("#importMeterReadingResultDiv2").show();
					$("#allImportCount2").html(data.result.totalCount);
					$("#successImportCount2").html(data.result.totalCount);
				}
			}
			hideProccessBar();
		}
	});
}

function initCommunity() {
	$("#cidSelect").select2({
		placeholder : '请选择小区',
		language : "zh-CN",
		allowClear : true,
		ajax : {
			url : '/CMS/select/getCommunityList.ht',
			dataType : 'json',
			delay : 250,
			data : function(param) {
				return {
					search : param.term,
					page : param.page || 1,
					showAllItem : true
				};
			},
			processResults : function(data, param) {
				param.page = data.pageNum;
				return {
					results : data.list,
					pagination : {
						more : data.hasNextPage
					}
				};
			}
		},
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#cid").val(obj.id || '');
			return obj.name || obj.text;
		}
	});

	$("#cidSelect").change(function() {
		$('#hidSelect').select2('val', '');
		$("#hid").val('');
		$('#hidSelect').empty();
	});
}

function initHouse() {
	$("#hidSelect").select2({
		placeholder : '请选择房号',
		language : "zh-CN",
		allowClear : true,
		ajax : {
			url : '/CMS/select/getHouseList.ht',
			dataType : 'json',
			delay : 250,
			data : function(param) {
				return {
					search : param.term,
					page : param.page || 1,
					cid : function() {
						return $("#cid").val() || '';
					},
					showAllItem : true
				};
			},
			processResults : function(data, param) {
				param.page = data.pageNum;
				return {
					results : data.list,
					pagination : {
						more : data.hasNextPage
					}
				};
			}
		},
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#hid").val(obj.id || '');
			return obj.name || obj.text;
		}
	});
}

var _BUILDING_ARRAY = [];
function getBuildingArray(cid) {
	if (!cid || cid == '') {
		return;
	}
	$.ajax({
		url : '/CMS/billInfoHouseList/dynamicPlot.ht',
		data : {
			cid : cid
		},
		dataType : 'json',
		success : function(data) {
			_BUILDING_ARRAY = data ? data : [];

			initExportBuildingNo();
		}
	});
}

function initExportBuildingNo() {
	var objMap = {};
	var array = [];
	for ( var i in _BUILDING_ARRAY) {
		var buildingObj = _BUILDING_ARRAY[i];
		var buildingNo = buildingObj[1];
		if (!objMap[buildingNo]) {
			objMap[buildingNo] = buildingNo;

			// 下拉列表值
			var buildingNoMap = {};
			buildingNoMap.id = buildingNo;
			buildingNoMap.name = buildingNo;
			buildingNoMap.text = buildingNo;
			array.push(buildingNoMap);
		}
	}

	// 清空下拉列表
	$("#export_buildingUnitSelect").empty();

	$("#export_buildingNoSelect").select2({
		placeholder : '请选择楼栋',
		language : "zh-CN",
		allowClear : true,
		data : array,
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#export_buildingNo").val(obj.id || '');
			return obj.name || obj.text;
		}
	});

	$("#export_buildingNoSelect").bind('change', function() {
		initExportBuildingUnit($(this).val() || '');
	});

	$("#export_buildingNoSelect").select2('val', '');
}

// 初始化单元下拉列表
function initExportBuildingUnit(value) {

	// 用与去重复
	var objMap = {};

	var array = [];
	for ( var i in _BUILDING_ARRAY) {
		var buildingObj = _BUILDING_ARRAY[i];

		var buildingNo = buildingObj[1];
		var buildingUnit = buildingObj[2];
		if (buildingNo == value) {
			if (!objMap[buildingUnit]) {
				objMap[buildingUnit] = buildingUnit;

				// 下拉列表值
				var buildingUnitMap = {};
				buildingUnitMap.id = buildingUnit;
				buildingUnitMap.name = buildingUnit;
				buildingUnitMap.text = buildingUnit;
				array.push(buildingUnitMap);
			}
		}
	}

	// 清空下拉列表
	$("#export_buildingUnitSelect").empty();

	$("#export_buildingUnitSelect").select2({
		placeholder : '请选择单元',
		language : "zh-CN",
		allowClear : true,
		data : array,
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#export_buildingUnit").val(obj.id || '');
			return obj.name || obj.text;
		}
	});

	$("#export_buildingUnitSelect").bind('change', function() {
		initExportBuildingNum(value, $(this).val() || '');
	});

	$("#export_buildingUnitSelect").select2('val', '');
}

function initExportBuildingNum(value1, value2) {

	// 用与去重复
	var objMap = {};
	var array = [];
	for ( var i in _BUILDING_ARRAY) {
		var buildingObj = _BUILDING_ARRAY[i];

		var buildingNo = buildingObj[1];
		var buildingUnit = buildingObj[2];
		var buildingNum = buildingObj[3];
		var hid = buildingObj[4];
		if (buildingNo == value1 && buildingUnit == value2) {
			if (!objMap[hid]) {
				objMap[hid] = hid;

				// 下拉列表值
				var buildingNumMap = {};
				buildingNumMap.id = hid;
				buildingNumMap.name = buildingNum;
				buildingNumMap.text = buildingNum;
				array.push(buildingNumMap);
			}
		}
	}

	// 清空
	$("#export_buildingNumSelect").empty();

	$("#export_buildingNumSelect").select2({
		placeholder : '请选择房号',
		language : "zh-CN",
		allowClear : true,
		data : array,
		escapeMarkup : function(markup) {
			return markup;
		},
		templateResult : formatRepo,
		templateSelection : function(obj) {
			$("#export_buildingNum").val(obj.id || '');
			return obj.name || obj.text;
		}
	});

	$("#export_buildingNumSelect").select2('val', '');

}

function checkForm() {
	if (userType == '3') {
		if (($("#hid").val() || '') == '') {
			_alert("请选择房号")
			return false;
		}
	} else {
		if (($("#cid").val() || '') == '') {
			_alert("请选择小区");
			return false;
		}
	}
}